package models

import (
	"gitee.com/sansaniot/ssiot-core/httpmvc/model"
	"gorm.io/gorm"

	cDto "ssdevice/common/dto"
	"ssdevice/internal/device/models/query"
)

type SysProtocol struct {
	Id          int     `json:"id" gorm:"primaryKey;type:int4"`
	Pid         int     `json:"pid" gorm:"type:int2"`
	Label       string  `json:"label" gorm:"type:varchar(255)"`
	Value       *string `json:"value" gorm:"type:varchar(255)"`
	Type        *string `json:"type" gorm:"type:varchar(255)"`
	GateProduct *string `json:"gateProduct" gorm:"type:varchar(255)"`

	model.Model
}

func (SysProtocol) TableName() string {
	return "sys_protocol"
}

func (e *SysProtocol) Generate() interface{} {
	o := *e
	return &o
}

func (e *SysProtocol) GetId() interface{} {
	return e.Id
}

func (e *SysProtocol) FindProtoList(req *query.SysProtoQuery) (err error, result interface{}) {
	list := make([]SysProtocol, 0)
	var count int64
	if req.PageIndex > 0 && req.PageSize > 0 {
		err = e.FindPage(&list, &count,
			cDto.MakeCondition(req.GetNeedSearch()),
			cDto.OrderDest("id", false, req.OrderBy),
			cDto.Paginate(req.GetPageSize(), req.GetPageIndex()),
		)
		result = &cDto.Page{
			Records:   list,
			Total:     count,
			PageSize:  req.GetPageSize(),
			PageIndex: req.GetPageIndex(),
			Pages:     (count + int64(req.GetPageSize()) - 1) / int64(req.GetPageSize()),
			Other:     nil,
		}
	} else {
		err = e.FindList(&list,
			cDto.MakeCondition(req.GetNeedSearch()),
			cDto.OrderDest("id", false, req.OrderBy),
		)
		result = list
	}
	return
}

func (e *SysProtocol) FindProtocolMap(db *gorm.DB, value ...string) (result map[string]SysProtocol) {
	if db != nil {
		e.Orm = db
	}
	list := make([]SysProtocol, 0)
	q := query.SysProtoQuery{}
	if len(value) > 0 && len(value[0]) > 0 {
		q.Value = value[0]
	}
	_ = e.FindList(&list, cDto.MakeCondition(q))
	result = make(map[string]SysProtocol)
	for i, protocol := range list {
		if protocol.Value == nil {
			continue
		}
		result[*protocol.Value] = list[i]
	}
	return
}

func (e *SysProtocol) FindGateModelMap(db *gorm.DB, pdmodel ...string) (result map[string]SysProtocol) {
	if db != nil {
		e.Orm = db
	}
	list := make([]SysProtocol, 0)
	q := query.SysProtoQuery{}
	if len(pdmodel) > 0 && len(pdmodel[0]) > 0 {
		q.GateProduct = pdmodel[0]
	}
	_ = e.FindList(&list, cDto.MakeCondition(q))
	result = make(map[string]SysProtocol)
	for i, protocol := range list {
		if protocol.GateProduct == nil {
			continue
		}
		result[*protocol.GateProduct] = list[i]
	}
	return
}
